package com.graduation.alien_yuan.smartmusicplayer;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.graduation.alien_yuan.smartmusicplayer.adapters.LocalMusicListAdapter;
import com.graduation.alien_yuan.smartmusicplayer.bean.MusicModel;
import com.graduation.alien_yuan.smartmusicplayer.utils.LogUtils;
import com.graduation.alien_yuan.smartmusicplayer.utils.Utils;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private PlayerStateUpdateReceiver playerStateUpdateReceiver;
    private MusicModel currentMusicModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        playerStateUpdateReceiver =new PlayerStateUpdateReceiver();
        IntentFilter intentFilter=new IntentFilter();
        intentFilter.addAction(PlayerService.ACTION_UPDATE_TRACK);
        intentFilter.setPriority(0);
        registerReceiver(playerStateUpdateReceiver, intentFilter);


        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        navigationView.getHeaderView(0).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                startActivity(intent);
            }
        });

        initUI();
        Intent intent = new Intent(PlayerService.ACTION_PLAY_CTRL);
        startService(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(playerStateUpdateReceiver);
    }

    private RecyclerView recyclerView;
    private LocalMusicListAdapter mMusicAdapter;
    private TextView titleTextView;
    private SeekBar seekBar;
    private ToggleButton toggleButton;
    private View nextButton;
    private View previousButton;
    private void initUI(){
        titleTextView = (TextView)findViewById(R.id.main_play_title);
        seekBar = (SeekBar)findViewById(R.id.main_play_seekbar);
        toggleButton = (ToggleButton)findViewById(R.id.main_play_toggle);
        recyclerView = (RecyclerView)findViewById(R.id.recycle_view);
        nextButton = findViewById(R.id.main_play_next);
        previousButton = findViewById(R.id.main_play_previous);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        ArrayList<MusicModel> list = Utils.getMusicModelList(this);
        mMusicAdapter = new LocalMusicListAdapter(this,list);
        recyclerView.setAdapter(mMusicAdapter);
        mMusicAdapter.setOnItemClickListener(new LocalMusicListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Toast.makeText(MainActivity.this, "onItemClick:" + position, Toast.LENGTH_SHORT).show();
                play(mMusicAdapter.getItemObject(position).get_id(), position);
            }

            @Override
            public boolean onItemLongClick(View view, int position) {
                Toast.makeText(MainActivity.this, "onItemLongClick:" + position, Toast.LENGTH_SHORT).show();
                return false;
            }
        });
        toggleButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playCtrlClick(v.getId());
            }
        });
        nextButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playCtrlClick(v.getId());
            }
        });
        previousButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playCtrlClick(v.getId());
            }
        });
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_local_music) {
            // Handle the camera action
        } else if (id == R.id.nav_listening_test) {
            Intent intent = new Intent(MainActivity.this,ListeningTestActivity.class);
            startActivity(intent);

        } else if (id == R.id.nav_smart_pattern) {

        } else if (id == R.id.nav_config) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    private void play(String id,int position){
        PlayerService.currentPosition = position;
        Intent intent = new Intent();
        intent.setAction(PlayerService.ACTION_PLAY_CTRL);
        intent.putExtra(PlayerService.KEY_INTENT_FROM, PlayerService.VALUE_MUSIC_SELECTED);
        intent.putExtra(PlayerService.KEY_CURRENT_POSITION,position);
        intent.putExtra(PlayerService.KEY_ID,id);
        sendBroadcast(intent);
    }

    private void playCtrlClick(int view_id){
        Intent intent = new Intent();
        intent.setAction(PlayerService.ACTION_PLAY_CTRL);
        intent.putExtra(PlayerService.KEY_INTENT_FROM, PlayerService.VALUE_CTRL);
        intent.putExtra(PlayerService.KEY_CTRL_ID,view_id);
        sendBroadcast(intent);
    }


    public class PlayerStateUpdateReceiver extends BroadcastReceiver
    {
        @Override
        public void onReceive(Context context, Intent intent){
            LogUtils.d("alien-PlayerStateUpdateReceiver:" + intent.toString());
            boolean isPlaying = intent.getBooleanExtra("isPlaying",false);
            int currentProgress = intent.getIntExtra("currentProgress", 0);
            int duration = intent.getIntExtra("duration",0);
            titleTextView.setText(Utils.getMusicModelList(getApplicationContext()).get(PlayerService.currentPosition).getTitle());
            toggleButton.setChecked(isPlaying);
            seekBar.setMax(duration);
            seekBar.setProgress(currentProgress);
        }

    }
}
